package com.ruoyi.bim.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bim.utils.HttpClient;
import com.ruoyi.framework.shiro.token.LoginType;
import com.ruoyi.framework.shiro.token.UserToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Controller
@RequestMapping("/bimService")
public class BAMOAuthController {
    @Value("${oauth.clientId}")
    private String clientId;
    @Value("${oauth.clientSecret}")
    private String clientSecret;
    @Value("${oauth.bamDomain}")
    private String bamDomain;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(HttpServletRequest request){
        return request.getHeader("user-agent");
    }

    @RequestMapping("/oAuth2Login")
    public String oauthLogin(HttpServletRequest request,
                             HttpServletResponse response,
                             String code) throws IOException {
        //跳转到BAM认证地址
        if (code == null) {
            String uri = "";
            uri = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
            String url = bamDomain +
                    "/oauth2/authorize?" +
                    "client_id=" + clientId +
                    "&redirect_uri=" + uri + "bimService/oAuth2Login/" +
                    "&response_type=code" +
                    "&state=123456";
            response.sendRedirect(url);
            return null;
        }


        //BAM认证成功，通过code授权码获取Token
        String getTokenUrl = bamDomain +
                "/oauth2/getToken?" +
                "client_id=" + clientId +
                "&grant_type=authorization_code" +
                "&code=" + code +
                "&client_secret=" + clientSecret;
        HttpClient client = new HttpClient();
        String getTokenResponeStr = client.postJson(getTokenUrl, "");
        JSONObject getTokenResponseJson = JSON.parseObject(getTokenResponeStr);
        String accessToken = getTokenResponseJson.getString("access_token");
        String uid = getTokenResponseJson.getString("uid");

        //通过Token和UID获取用户信息
        String getUserInfoUrl = bamDomain +
                "/oauth2/getUserInfo?" +
                "access_token=" + accessToken +
                "&client_id=" + clientId +
                "&uid=" + uid;
        String getUserInfoResponseStr = client.getJson(getUserInfoUrl);
        JSONObject getUserInfoResponseJson = JSON.parseObject(getUserInfoResponseStr);
        String userName = Objects.toString(getUserInfoResponseJson.get("loginName"), "");
        JSONArray spRoleList = (JSONArray) getUserInfoResponseJson.get("spRoleList");
        if(spRoleList.size() == 0){
            return "error/errorsprole";
        }
        userName = Objects.toString(spRoleList.get(0),"");
        Subject subject = SecurityUtils.getSubject();
        UserToken usernamePasswordToken = new UserToken(userName.trim(), LoginType.NOPASSWD);
        try {
            subject.login(usernamePasswordToken);
            return "OAuth2Index";
        } catch (AuthenticationException e) {
            return "error/unauth";
        }
    }
}
